import pickle
from sc_engine.repositories import Repository

class IdGenRepository(object):
    START_ID = 1

    def __init__(self, store):
        self.store = store

        if 'next_id' not in store:
            self.store['next_id'] = 1

        if 'data' not in store:
            self.store['data'] = {}
        self.data = self.store['data']

    def add(self, key):
        pickled_key = pickle.dumps(key)

        if pickled_key in self.data:
            id = self.data[pickled_key]
            msg = "Key %s is already in store with id %s" % (key, id)
            raise ValueError(msg)

        id = self.data[pickled_key] = self.store['next_id']
        self.store['next_id'] += 1

        return id

    def __getitem__(self, key):
        pickled_key = pickle.dumps(key)
        if pickled_key not in self.data:
            raise KeyError(key)
        return self.data[pickle.dumps(key)]

    def __contains__(self, key):
        return pickle.dumps(key) in self.data
